package game.services.session;

import com.google.protobuf.GeneratedMessageV3;
import dou.net.ThreadPoolManager;
import dou.net.protocol.AbstractProtocol;
import dou.net.socket.IClientSocket;
import dou.net.socket.InvalidProtocolException;
import game.services.MsgID;
import game.services.session.handler.SessionSendKeepAliveHandler;
import game.services.session.handler.SessionSendLoginHandler;
import game.services.session.handler.SessionSendLogoutHandler;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.util.concurrent.ThreadPoolExecutor;

public class SessionProtocol extends AbstractProtocol
{
    private static Logger logger = LogManager.getLogger("GameServer");

    private static final String PROTOCOL_NAME = "SessionProtocol";

    private ThreadPoolExecutor _threadPoolExecutor;

    public SessionProtocol()
    {
        super();
        _threadPoolExecutor = ThreadPoolManager.getInstance().getServiceHandlerPool(PROTOCOL_NAME);
    }

    public SessionProtocol(int coreSize, int maxSize, long keepTime, int priority)
    {
        super();
        _threadPoolExecutor = ThreadPoolManager.getInstance().getServiceHandlerPool(PROTOCOL_NAME, coreSize, maxSize, keepTime, priority);
    }

    @Override
    protected void initMessageHandlers()
    {
        try
        {
            this.registerMessageHandler(MsgID.Req_SessionKeepAlive.value(), SessionSendKeepAliveHandler.class);
            this.registerMessageHandler(MsgID.Req_SessionLogin.value(), SessionSendLoginHandler.class);
            this.registerMessageHandler(MsgID.Req_SessionLogout.value(), SessionSendLogoutHandler.class);
        }
        catch(Exception exception)
        {
            logger.error("Register message handler error! ", exception);
        }
    }

    @Override
    public void messageHandler(int msgID, int msgNum, byte[] bytes, IClientSocket socket) throws InvalidProtocolException
    {
        try
        {
            _threadPoolExecutor.execute(new SessionHandlerRunnable(msgID, msgNum, bytes, socket, this));
        }
        catch(Exception exception)
        {
            logger.error("Protocol \"" + getClass().getName() + "\" execute error: ", exception);
        }
    }

    @Override
    public void messageHandler(int msgID, int msgNum, GeneratedMessageV3 message, IClientSocket socket) throws InvalidProtocolException
    {
        try
        {
            _threadPoolExecutor.execute(new SessionHandlerRunnable(msgID, msgNum, message, socket, this));
        }
        catch(Exception exception)
        {
            logger.error("Protocol \"" + getClass().getName() + "\" execute error: ", exception);
        }
    }

    @Override
    public void cleanup()
    {
        _threadPoolExecutor.shutdown();
    }
}
